import gtk
import os.path
import gnomevfs

from common.lib import Singleton

class FileMimetype(Singleton):
    '''to be used like this: image.set_from_icon_name(filemimetype.get_icon(filename.path))'''
    def __init__(self):
        self.all_icons = gtk.icon_theme_get_default().list_icons()
        self.cache = {}
        
    def get_type(self, path=None):
        if path == None or not os.path.exists(path):
            return 'text-plain'
        return gnomevfs.get_mime_type(path).replace('/','-')
    
    def get_icon_name(self, path=None):
        if path == None or not os.path.exists(path):
            return gtk.STOCK_FILE
        
        mime_type = self.get_type(path)
        
        if mime_type in self.cache:
            return self.cache[mime_type]
        
        items = mime_type.split('-')
        for i in xrange(len(items) - 1):
            icon_name = "gnome-mime-" + '-'.join(items[:len(items) - i])
            if icon_name in self.all_icons:
                self.cache[mime_type] = icon_name
                return icon_name
        
        if os.path.isdir(path):
            icon_name = 'folder'
            if icon_name in self.all_icons:
                self.cache[mime_type] = icon_name
                return icon_name
            
        for i in xrange(len(items) - 1):
            icon_name = '-'.join(items[:len(items) - i])
            if icon_name in self.all_icons:
                self.cache[mime_type] = icon_name
                return icon_name
            
        icon_name = gtk.STOCK_FILE
        self.cache[mime_type] = icon_name
        return icon_name
        
        
filemimetype = FileMimetype.get_instance()
def get_gtk_image_new_from_icon_name(name=gtk.STOCK_FILE, size=gtk.ICON_SIZE_BUTTON):
    return gtk.image_new_from_icon_name(name ,size)

def get_gtk_image_new_from_path(path=None, size=gtk.ICON_SIZE_BUTTON):
    icon_name = filemimetype.get_icon_name(path)
    return get_gtk_image_new_from_icon_name(icon_name, size)